import PermTree from '@/components/PermTree'
import regex from '@/constants/Regex'
import { tenantModel } from '@/models/tenant'
import { TenantVO } from '@/services/TenantService'
import { useModel } from '@@/exports'
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components'
import { ProFormInstance } from '@ant-design/pro-form/lib'
import { RequestOptionsType } from '@ant-design/pro-utils'
import { Divider } from 'antd/lib'
import { observer } from 'mobx-react'
import { useRef, useState } from 'react'

export interface TenantUpdateModalProps {
  onFinish: (formData: any) => Promise<boolean | void>
  tenant?: TenantVO
  open: boolean
  onOpenChange: (state: boolean) => void
}

const TenantUpdateModal = (props: TenantUpdateModalProps) => {
  let { getDictList, getDictEnum } = useModel('dict')

  let [permKeys, setPermKeys] = useState([] as number[])

  const formRef = useRef<ProFormInstance>()
  const [inst, setInst] = useState<TenantVO | undefined>()

  const onOpenChange = (state: boolean) => {
    if (state) {
      let dto = props.tenant || undefined
      setPermKeys([])
      setInst(dto)
      formRef?.current?.setFieldsValue(dto)
    } else {
      setInst(undefined)
      formRef?.current?.resetFields()
    }
    props.onOpenChange(state)
  }
  return (
    <>
      <ModalForm
        formRef={formRef}
        title={props.tenant ? '修改租户' : '添加租户'}
        open={props.open}
        initialValues={inst}
        onFinish={props.onFinish}
        onOpenChange={onOpenChange}
      >
        <ProFormText label="id" hidden name="id" />
        <ProFormText label="租户名" name="tenantName" />
        <ProFormSelect
          label="状态"
          name="status"
          request={async () => getDictList('tenant_status') as RequestOptionsType[]}
        />
        <ProFormText
          label="管理员手机号"
          name="adminPhone"
          rules={[
            { required: true, message: '密码不能为空' },
            {
              pattern: regex.PHONE,
              message: '请输入正确的手机号码',
            },
          ]}
        />
        <ProFormText label="管理员密码" name="adminPassword" rules={[{ required: true, message: '密码不能为空' }]} />
        <Divider>角色权限</Divider>
        <PermTree
          data={tenantModel.menuTree}
          onCheck={tenantModel.setSelectMenuKey}
          selectKeys={tenantModel.selectMenuKey}
        />
      </ModalForm>
    </>
  )
}
export default observer(TenantUpdateModal)
